package io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class MutilThreadDownLoad {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String inputPath = "G:/下载/formatfactory.zip";
		String outputPath = "E:/TestFile/formatfactory.zip";
		int threadNum = 5;
		download(inputPath, outputPath, threadNum);

	}

	private static void download(String inputPath, String outputPath,
			int threadNum) {
		File inputFile = new File(inputPath);
		if (!inputFile.isFile()) {
			System.out.println("输入文件不存在！");
			return;
		}
		long size = inputFile.length();
		File outputFile = new File(outputPath);
		if (!outputFile.exists()) {
			try {
				outputFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		RandomAccessFile raf;
		try {
			raf = new RandomAccessFile(outputFile, "rwd");
			raf.setLength(size);
			raf.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long block = size / threadNum==0?size/threadNum:size/threadNum+1;
				

		for (int i = 0; i < threadNum; i++) {
			final int threadID = i;
			new DownLoadThread(threadID, block, inputFile, outputFile).start();
		}

	}

}

class DownLoadThread extends Thread {

	private int threadID;
	private long block;
	private File inputFile;
	private File outputFile;

	public DownLoadThread(int threadID, long block, File inputFile,
			File outputFile) {
		this.threadID = threadID;
		this.block = block;
		this.inputFile = inputFile;
		this.outputFile = outputFile;
	}

	public void run() {
		long start = threadID* block;
		RandomAccessFile inputRAF = null;
		RandomAccessFile outputRAF = null;
		try {
			inputRAF = new RandomAccessFile(inputFile, "rwd");
			outputRAF = new RandomAccessFile(outputFile, "rwd");
			inputRAF.seek(start);
			outputRAF.seek(start);
			byte[] buff = new byte[1024];
			int length = 0;
			int totlelength = 0;
			System.out.println("线程 "+threadID+" 开始下载数据!");
			while (totlelength<block&&(length = inputRAF.read(buff)) != -1) {
				outputRAF.write(buff, 0, length);
				totlelength+=length;
			}
			System.out.println("线程 "+threadID+" 完成下载数据!");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(inputRAF!=null){
				try {
					inputRAF.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(outputRAF!=null){
				try {
					outputRAF.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}